package com.sx.gongzhong;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.sx.gongzhong.activity.LoginActivity;
import com.sx.gongzhong.model.PublicBean;
import com.sx.gongzhong.model.PublicTotalBean;
import com.sx.gongzhong.pest.ReportAndForbiddenPest;
import com.sx.gongzhong.port.PermissionsResultListener;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.InitData;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.widget.MyPopupWindow;
import com.sx.gongzhong.widget.ReportDialog;
import com.sx.gongzhong.widget.SystemBarTintManager;

import java.util.ArrayList;
import java.util.List;

import xiaofei.library.datastorage.DataStorageFactory;

/**
 * Created by XZY on 2017/11/21.
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected FrameLayout rootContent;
    Toolbar toolbar;
    TextView title_name;
    ImageView title_back,title_Right,title_Right2;
    TextView tvRight;
    int barheight = 0;
    public SystemBarTintManager mBaseTintManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mBaseTintManager = new SystemBarTintManager(this);
            mBaseTintManager.setTranslucentStatus(this, true); //设置沉溺式
            mBaseTintManager.setStatusBarTintEnabled(false);    //设置透明
        }
        MyApplication.instance.addActivity(this);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
//                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN );
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setUI(savedInstanceState);
    }

    public abstract void setUI(Bundle savedInstanceState);

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(R.layout.activity_base);
        rootContent = (FrameLayout) this.findViewById(R.id.content);
        toolbar = (Toolbar) this.findViewById(R.id.toolbar);
        title_name = (TextView) this.findViewById(R.id.tv_title);
        title_back = (ImageView) this.findViewById(R.id.imv_Left);
        title_Right = (ImageView) this.findViewById(R.id.imv_Right);
        title_Right2 = (ImageView) this.findViewById(R.id.imv_Right2);
        tvRight=(TextView) this.findViewById(R.id.tv_right);
     //   tvLeft=(TextView) this.findViewById(R.id.tv_Left);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//&& Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP
            barheight = BaseUtil.CheckStatusBarHeight(getApplicationContext());
            ViewGroup contentView = (ViewGroup) findViewById(android.R.id.content);
            int color = getResources().getColor(R.color.style_color);
            View statusBarView = new View(this);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    barheight);
            statusBarView.setBackgroundColor(color);
            contentView.addView(statusBarView, lp);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.style_color));
            }
        }
//        toolbar.setPadding(0, barheight, 0, 0);
        setBack();
        View.inflate(this, layoutResID, rootContent);
    }

    /**
     * 左侧返回
     */
    protected void setBack(){
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUtil.hintKb(BaseActivity.this);
                finish();
            }
        });

    }
    /**
     * 隐藏标题栏
     */
    public void setGoneTitle() {
        toolbar.setVisibility(View.GONE);
//        rootContent.setPadding(0, barheight, 0, 0);
    }

    /**
     * 设置返回隐藏
     */
    protected void setBackHide() {
        title_back.setVisibility(View.GONE);
    }

    /**
     * 设置返回显示
     */
    protected void setBackShow() {
        title_back.setVisibility(View.VISIBLE);
    }

    /**
     * 设置title
     */
    protected void setTitleName(String title) {
        title_name.setText(title);
    }

    /**
     * 设置标题带左侧图片
     * @param title 标题
     * @param resourcesId 左图
     */
    protected void setTitleName(String title,int resourcesId) {
        title_name.setText(title);
        Drawable drawable=getResources().getDrawable(resourcesId);
        drawable.setBounds( 0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
        title_name.setCompoundDrawables(null,null,drawable,null);
    }

    /**
     * 设置title
     */
    protected void setTitleName(int id) {
        title_name.setText(id);
    }

//    /**
//     * 设置左侧文字
//     * @param resourcesId 文字id
//     */
//    protected void setTitleLeft(int resourcesId) {
//        if (tvLeft.getVisibility()!=View.VISIBLE){
//            tvLeft.setVisibility(View.VISIBLE);
//            title_back.setVisibility(View.GONE);
//        }
//      tvLeft.setText(resourcesId);
//    }
//
//    /**
//     * 设置左侧文字
//     * @param str 标题
//     */
//    protected void setTitleLeft(String str) {
//        if (tvLeft.getVisibility()!=View.VISIBLE){
//            tvLeft.setVisibility(View.VISIBLE);
//            title_back.setVisibility(View.GONE);
//        }
//        tvLeft.setText(str);
//    }

    /**
     * 设置左侧图片
     * @param resourcesId 图标id
     */
    protected void setLeftImage(int resourcesId) {
        title_back.setImageResource(resourcesId);
        title_back.setOnClickListener(null);
    }

    /**
     * 设置右侧文字
     */
    protected void setTitleRight(String title) {
        if (tvRight.getVisibility()!=View.VISIBLE){
            tvRight.setVisibility(View.VISIBLE);
        }
        tvRight.setText(title);
    }
    /**
     * 设置右侧文字
     */
    protected void setTitleRight(int resourcesId) {
        if (tvRight.getVisibility()!=View.VISIBLE){
            tvRight.setVisibility(View.VISIBLE);
        }
        tvRight.setText(resourcesId);
    }

    /**
     * 设置右侧图片
     * @param resourcesId 图标id
     */
    protected void setRightImage(int resourcesId) {
        if (title_Right.getVisibility()!=View.VISIBLE){
            title_Right.setVisibility(View.VISIBLE);
        }
        title_Right.setImageResource(resourcesId);
    }

    /**
     * 设置右侧2图片
     * @param resourcesId 图标id
     */
    protected void setRightImage2(int resourcesId) {
        if (title_Right2.getVisibility()!=View.VISIBLE){
            title_Right2.setVisibility(View.VISIBLE);
        }
        title_Right2.setImageResource(resourcesId);
    }

    /**
     * 设置右侧2图片显示
     */
    protected void setRightImage2Show() {

        title_Right2.setVisibility(View.VISIBLE);

    }
    /**
     * 设置右侧2图片隐藏
     */
    protected void setRightImage2Hide() {
        title_Right2.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        MyApplication.instance.removeActivity(this);
        super.onDestroy();
    }

    private int mRequestCode;
    /**权限回调的接口*/
    private PermissionsResultListener mListener;
    /**
     * 其他 Activity 继承 BaseActivity 调用 performRequestPermissions 方法
     *
     * @param permissions 要申请的权限数组
     * @param requestCode 申请标记值
     * @param listener    实现的接口
     */
    protected void performRequestPermissions(String[] permissions, int requestCode,
                                             PermissionsResultListener listener) {
        if (permissions == null || permissions.length < 1) {
            return;
        }
        mRequestCode = requestCode;
        mListener = listener;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取未通过的权限列表
            String[] newPermissions = checkEachSelfPermission(permissions);
            if (newPermissions.length > 0) {
                ActivityCompat.requestPermissions(this, newPermissions, mRequestCode);
            } else {
                if (mListener != null) {
                    mListener.onPermissionGranted();
                }
            }
        } else {
            if (mListener != null) {
                mListener.onPermissionGranted();
            }
        }
    }

    /**
     * 检察每个权限是否申请
     *
     * @return 返回未申请的权限
     */
    private String[] checkEachSelfPermission(String... permissions) {
        List<String> newPermissions = new ArrayList<String>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                newPermissions.add(permission);
            }
        }
        return newPermissions.toArray(new String[newPermissions.size()]);
    }

    /**
     * 请求权限的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode) {
            boolean b=checkEachPermissionsGranted(grantResults);
            if (b) {//全部通过
                mListener.onPermissionGranted();
            } else {// 用户拒绝申请权限
                mListener.onPermissionDenied();
                ToastUtils.showToast(BaseActivity.this, "您拒绝授权,会导致应用无法正常使用可以在系统设置中重新开启权限");
            }
        }

    }
    /**
     * 检查回调结果
     *
     * @param grantResults
     * @return
     */
    private boolean checkEachPermissionsGranted(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public boolean isLogin(){
        if (MyApplication.instance.userBean == null || BaseUtil.isEmpty(MyApplication.instance.userBean.sid)) {
            Intent intent = new Intent(MyApplication.context, LoginActivity.class);
            startActivity(intent);
            return false;
        }
        return true;
    }
    /**
     * 显示权限操作弹窗
     * @param publishUserId 发帖子ID
     *  @param handStatus 帖子状态（用于诉求 互帮互助）
     */
    public MyPopupWindow popupWindow;
    private View view;
    public void createPop(String publishUserId,String handStatus) {
        if (popupWindow==null){
            view = LayoutInflater.from(this).inflate(R.layout.pop_comment, null);
            popupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            popupWindow.setTouchable(true);
            popupWindow.setOutsideTouchable(false);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
            view.findViewById(R.id.tv_Close).setOnClickListener(this);
            view.findViewById(R.id.tv_evaluation).setOnClickListener(this);
            view.findViewById(R.id.tv_ShutUp).setOnClickListener(this);
            view.findViewById(R.id.tv_Report).setOnClickListener(this);
            view.findViewById(R.id.tv_Delete).setOnClickListener(this);
            view.findViewById(R.id.tv_Cancel).setOnClickListener(this);
        }
        if ("general".equalsIgnoreCase(MyApplication.instance.userBean.userType.code)){//普通用户
            view.findViewById(R.id.tv_ShutUp).setVisibility(View.GONE);//禁言
            if (!publishUserId.equals(MyApplication.instance.userBean.id)){//不是楼主
                view.findViewById(R.id.tv_Delete).setVisibility(View.GONE);//删除
            }
        }
        if (!BaseUtil.isEmpty(handStatus)){
            if (handStatus.equals("undelte")){//楼主 管理员 不能删除
                view.findViewById(R.id.tv_Delete).setVisibility(View.GONE);
                view.findViewById(R.id.tv_evaluation).setVisibility(View.GONE);
            }else if (handStatus.equals("appeal_undelte_caneval")) { //评价 且 不能删除
                view.findViewById(R.id.tv_Delete).setVisibility(View.GONE);
                if (publishUserId.equals(MyApplication.instance.userBean.id)) {//楼主 才可评价
                    view.findViewById(R.id.tv_evaluation).setVisibility(View.VISIBLE);
                }
            }else if (handStatus.equals("help_can_close_delete")){ //待解决 状态可关闭 删除(互帮互助)
                if (publishUserId.equals(MyApplication.instance.userBean.id) ||
                        !"general".equalsIgnoreCase(MyApplication.instance.userBean.userType.code)){//楼主 管理员
                    view.findViewById(R.id.tv_Delete).setVisibility(View.VISIBLE);//删除
                    view.findViewById(R.id.tv_Close).setVisibility(View.VISIBLE);
                }
            }
        }
        popupWindow.showAsDropDown(findViewById(R.id.toolbar));
    }

    /**
     * @param type 举报 禁言
     * @param columnDataId reportDataId 被禁言 或 举报 的数据ID
     * @param columnType  举报 禁言模块
     */
    public void createReport(final String type, final String columnDataId,final String columnType) {
        PublicTotalBean bean =  DataStorageFactory.getInstance(getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE).load(PublicTotalBean.class,type);
        //获取到举报类型
        if (bean != null && bean.getChildren()!=null){
            ReportDialog.Builder builder=new ReportDialog.Builder(this);
            String title = "选择禁言时间";
            if ("reportType".equals(type)){
                title = "选择举报类型";
            }
            builder.setDataList(bean.getChildren()).setTitle(title)
                    .loadType(new ReportDialog.TypeCallback() {
                        @Override
                        public void backType(PublicBean publicBean) {
                            if ("reportType".equals(type)) {//举报
                                new ReportAndForbiddenPest(new IVoidView() {
                                    @Override
                                    public void voidView(String message) {
                                        ToastUtils.showToast(BaseActivity.this,message);
                                    }

                                    @Override
                                    public void showError(String message) {
                                        ToastUtils.showToast(BaseActivity.this,message);
                                    }
                                }).report(publicBean.getId(), columnType, columnDataId);
                            }
                            if ("forbiddenType".equals(type)) {//禁言
                                new ReportAndForbiddenPest(new IVoidView() {
                                    @Override
                                    public void voidView(String string) { //禁言成功
                                        ToastUtils.showToast(BaseActivity.this,string);
                                    }
                                    @Override
                                    public void showError(String message) {
                                        ToastUtils.showToast(BaseActivity.this,message);
                                    }
                                }).addForbidden(publicBean.getId(),columnType, columnDataId);
                            }
                        }
                    }).create().show();
        }else {
            new InitData(this).loadData();
            ToastUtils.showToast(this,"服务器异常 稍后再试");
        }
    }

    @Override
    public void onClick(View v) {

    }

}
